package com.wlgc.service.impl;

import com.wlgc.entity.RestBean;
import com.wlgc.entity.User;
import com.wlgc.service.FileService;
import com.wlgc.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
@Service
public class FileServiceImpl implements FileService {
    @Resource
    UserService userService;
    String legalFiles = ".png .jpg .jpeg";
    @Value("${Class_Study_path.image_path}")
    String base_path;
    @Override
    public RestBean changeAvatar(MultipartFile file) {
        String originalName  = file.getOriginalFilename();
        String fileName;
        String avatar_path;
        String suffix = originalName.substring(originalName.lastIndexOf("."));
        if(!legalFiles.contains(suffix)){
            return new RestBean(500,"非法文件格式，请上传.png .jpg .bmp .doc .docx .pdf格式文件");
        }
        User user = userService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        fileName=base_path+ File.separator+"avatar"+File.separator+ user.getUid()+suffix;
        avatar_path="image"+"/"+"avatar"+"/"+ user.getUid()+suffix;
        System.out.println(fileName);
        System.out.println(avatar_path);
        try{
            file.transferTo(new File(fileName));
            userService.changeAvatar_Path(user.getUid().intValue(),avatar_path);
        }
        catch (Exception e)
        {
            return new RestBean<>(500,"上传失败");
        }

        return new RestBean<>(200,"上传成功");
    }
}
